package com.example.sunran.auth;

import com.auth0.jwt.JWT;
import com.auth0.jwt.JWTVerifier;
import com.auth0.jwt.algorithms.Algorithm;
import com.auth0.jwt.interfaces.DecodedJWT;
import com.example.sunran.bean.User;
import sun.applet.Main;

import java.util.Calendar;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;

public class TokenCodeUtils {
    private static Algorithm algorithm = Algorithm.HMAC256("ALDsJsdFSLdsKADdsSF");

    private static Map<String, User> tokens = new HashMap<>();

    public static String generator(String id, User user){
        Calendar calendar = Calendar.getInstance();
        calendar.add(Calendar.DAY_OF_YEAR,3);
        Date d2 = calendar.getTime();


        String token = JWT.create()
                .withIssuer("sunran")
                .withJWTId(id)
                .withExpiresAt(d2)
                .sign(algorithm);

        tokens.put(id,user);

        return token;
    }


    public static String parse(String token){
        JWTVerifier verifier = JWT.require(algorithm).withIssuer("sunran").build();
        DecodedJWT decodedJWT = verifier.verify(token);
        String id = decodedJWT.getId();
        return id;
    }

    public static User getUserInfo(String id){
        return tokens.get(id);
    }

}
